Real DOM vs Virtual DOM in React JS – Detailed Notes
The Real DOM and Virtual DOM are important concepts in React JS. Understanding their differences helps developers understand how React updates web pages, manages UI changes, and avoids unnecessary DOM operations.
Course: JustAcademy React JS Training
Course Demo: Register for React JS Course Demo
1. What Is the DOM?
DOM stands for Document Object Model. It is a programming interface that represents an HTML document as a tree of objects. JavaScript can use the DOM to access and modify elements, text, attributes, and styles on a web page.
When a browser loads an HTML page, it creates a DOM tree representing the document structure.
Example of HTML
<div id="root">
<h1>Welcome to React JS</h1>
<p>Learn the DOM</p>
</div>
DOM Tree Representation
Document
|
└── html
|
└── body
|
└── div (id="root")
|
├── h1
| └── "Welcome to React JS"
|
└── p
└── "Learn the DOM"
The browser uses this structure to display the page. JavaScript can change the DOM to update what users see.
2. What Is the Real DOM?
The Real DOM is the actual Document Object Model maintained by the browser. It represents the elements and content currently present in a web page.
Developers can access and manipulate it using JavaScript DOM APIs such as getElementById(), querySelector(), createElement(), and appendChild().
Example: Updating the Real DOM Using JavaScript
<!DOCTYPE html>
<html>
<body>
<h1 id="heading">Hello World</h1>
<button onclick="changeText()">Change Text</button>
<script>
function changeText() {
document.getElementById("heading").textContent = "Hello React!";
}
</script>
</body>
</html>
Explanation
document.getElementById("heading") selects the heading element.
textContent accesses or changes the text inside the element.
- When the button is clicked, JavaScript changes the heading in the actual browser DOM.
Advantages of the Real DOM
- It is built into web browsers.
- It provides direct access to HTML elements.
- It supports event handling, forms, attributes, and styling.
- It is useful for small websites and situations requiring direct browser interaction.
Limitations of Direct DOM Manipulation
- Manually updating many elements can make complex applications harder to maintain.
- Developers must carefully coordinate changes to avoid inconsistent UI.
- Frequent DOM operations may contribute to performance problems, depending on what is changed and how the browser processes those changes.
- Managing UI updates manually becomes more difficult as application complexity increases.
3. What Is the Virtual DOM?
The Virtual DOM (VDOM) is a programming concept used by React to represent the UI in memory. React uses this representation to determine what changes are needed in the browser DOM when the UI output changes.
When a React component renders, it returns JSX describing the desired UI. React creates and compares internal representations of that UI, then commits the necessary changes to the actual DOM.
Important: The Virtual DOM is not a second browser DOM. It is an in-memory representation managed by React. It does not mean that every update is automatically faster in every situation.
Example of JSX in React
function App() {
return (
<div>
<h1>Welcome to React JS</h1>
<p>Learn the Virtual DOM</p>
</div>
);
}
export default App;
Explanation
- The component returns JSX describing the UI.
- React renders the component and calculates the resulting UI representation.
- When state or props change, React can render the component again.
- React compares the new result with the previous result and determines which DOM changes are necessary.
- React commits the required changes to the browser DOM.
Advantages of the Virtual DOM Approach
- Developers describe the UI instead of manually managing every DOM update.
- React calculates the necessary DOM changes.
- Component-based development helps organize complex interfaces.
- React can preserve existing DOM nodes and their state when appropriate.
- It makes UI updates easier to manage through state and props.
4. How the Virtual DOM Works in React
React generally updates the UI through a rendering and commit process. The following steps explain the basic idea.
Step 1: Initial Render
When the application starts, React renders the components and creates the required browser DOM nodes.
Step 2: State or Props Change
When relevant state or props change, React schedules a render so the component can describe the updated UI.
Step 3: Render the Updated UI
React calls the necessary component functions to calculate what the UI should look like now.
Step 4: Reconciliation
React compares the new rendered result with the previous one to work out which changes are needed. This process is commonly called reconciliation.
Step 5: Commit Changes to the Real DOM
React applies the necessary DOM changes. If the output has not changed, React may not need to modify the DOM at all.
Step 6: Browser Paint
The browser paints the updated page so the user can see the result.
Virtual DOM Update Flow
User Interaction
|
v
State or Props Change
|
v
React Renders Component
|
v
New UI Representation
|
v
Reconciliation
|
v
Required DOM Changes
|
v
Real DOM Updated
|
v
Browser Displays Updated UI
5. Real DOM vs Virtual DOM: Main Differences
| Basis |
Real DOM |
Virtual DOM |
| Meaning |
The actual document structure maintained by the browser. |
An in-memory representation of the UI used by React. |
| Location |
Managed by the browser. |
Managed internally by React in memory. |
| Representation |
Contains actual DOM nodes. |
Represents the UI through React's internal rendering structures. |
| Updates |
Can be updated directly using browser DOM APIs. |
React calculates required changes and commits them to the Real DOM. |
| Comparison |
Does not automatically compare a new UI description with a previous React render. |
React compares rendered results during reconciliation. |
| Developer work |
Direct DOM manipulation may require manual update logic. |
Developers generally describe the desired UI using components and JSX. |
| Performance |
Performance depends on the operations performed and the browser's work. |
Can reduce unnecessary DOM operations, but does not guarantee every application is faster. |
| UI management |
Can become difficult to coordinate manually in complex interfaces. |
Works with React's component, state, and props model. |
| Usage |
Used by browsers and accessible through JavaScript. |
Used by React to manage rendered UI updates. |
| Example |
document.querySelector("h1") |
return Hello; |
6. Example: Changing Text in Real DOM and React
A. Using the Real DOM with JavaScript
<h1 id="message">Hello World</h1>
<button onclick="updateMessage()">Update</button>
<script>
function updateMessage() {
document.getElementById("message").textContent = "Welcome!";
}
</script>
How it works: JavaScript directly selects the heading and changes its text in the browser DOM.
B. Using React and State
import { useState } from "react";
function App() {
const [message, setMessage] = useState("Hello World");
return (
<div>
<h1>{message}</h1>
<button onClick={() => setMessage("Welcome!")}>
Update
</button>
</div>
);
}
export default App;
How it works:
useState() stores the message in React state.
- The heading displays the current value of
message.
- Clicking the button calls
setMessage("Welcome!").
- React renders the component again and commits the required text change to the Real DOM.
Key difference: In the JavaScript example, the developer directly changes the DOM. In the React example, the developer updates state and React manages the corresponding DOM update.
7. What Is Reconciliation in React?
Reconciliation is the process React uses to determine how the current rendered UI differs from the previous rendered UI and what changes are required.
Example
Suppose the previous JSX is:
<h1 className="title">Hello</h1>
The updated JSX is:
<h1 className="title">Welcome</h1>
The element type and class remain the same, but the text changes. React can update the existing heading's text instead of replacing the entire page.
Why Reconciliation Matters
- It helps React identify changes between rendered UI results.
- It can avoid unnecessary DOM mutations.
- It helps React preserve existing elements when the tree structure allows it.
- It supports predictable UI updates when state and props change.
8. Does React Update the Entire DOM Every Time?
No. A component may render again, but that does not mean React replaces the entire browser DOM. React calculates the necessary changes and commits only those changes when possible.
For example, if only a heading's text changes, React may update that text while leaving an unrelated input element untouched.
Remember: A React re-render and a Real DOM update are different things. Rendering calculates the UI; committing applies required DOM changes.
9. Real DOM vs Virtual DOM: Advantages and Limitations
| Feature |
Real DOM |
Virtual DOM Approach |
| Direct control |
Provides direct access through browser APIs. |
React normally manages DOM updates for you. |
| Ease of UI development |
Manual update logic may be needed. |
State-driven components simplify many UI updates. |
| Complex interfaces |
Manual coordination can become difficult. |
Components help organize UI and its behavior. |
| Overhead |
Direct operations do not require React's reconciliation process. |
Rendering and reconciliation also require computation. |
| Performance |
Can be efficient for straightforward, targeted changes. |
Can efficiently calculate changes, depending on the application and update pattern. |
10. Common Misconceptions
- Misconception 1: The Virtual DOM is always faster than the Real DOM.
Correction: Performance depends on the work being done. React helps manage updates, but its rendering and reconciliation also have costs.
- Misconception 2: React creates a new browser DOM for every state update.
Correction: React can reuse existing DOM nodes and update only what is needed.
- Misconception 3: The Virtual DOM and Shadow DOM are the same.
Correction: The Virtual DOM is a UI representation used by libraries such as React. The Shadow DOM is a browser feature used to encapsulate parts of a DOM tree and their styles.
- Misconception 4: React components never use the Real DOM directly.
Correction: React normally manages DOM updates, but developers can access DOM nodes when needed, often through refs.
- Misconception 5: If a component renders again, every element on the page changes.
Correction: React can determine that no DOM update is necessary for unchanged output.
11. When Should You Use Direct DOM Manipulation?
In a React application, prefer updating the UI through state and props. Direct DOM access is still useful in specific situations, such as:
- Setting focus on an input field.
- Measuring an element's dimensions.
- Scrolling to a particular element.
- Integrating with a third-party library that requires a DOM node.
- Working with browser APIs that need a reference to an element.
Example Using useRef()
import { useRef } from "react";
function SearchBox() {
const inputRef = useRef(null);
function focusInput() {
inputRef.current.focus();
}
return (
<div>
<input ref={inputRef} placeholder="Enter a search term" />
<button onClick={focusInput}>Focus Input</button>
</div>
);
}
export default SearchBox;
Explanation: useRef() stores a reference to the input DOM node. Clicking the button calls focus() to move the cursor into the input field.
Avoid changing React-managed DOM nodes manually unless there is a specific reason. Manual changes can conflict with React's next update.
12. Real-World Example: Shopping Cart
Consider an e-commerce website where a user adds a product to a cart. The cart count changes from 0 to 1.
With Direct DOM Manipulation
JavaScript could select the cart-count element and manually update its text. As the application grows, developers must ensure that all related UI elements remain in sync.
With React
The cart count can be stored in state. When the user adds a product, the state changes and React updates the relevant UI to match the new state.
import { useState } from "react";
function Cart() {
const [cartCount, setCartCount] = useState(0);
return (
<div>
<h2>Shopping Cart</h2>
<p>Items in cart: {cartCount}</p>
<button onClick={() => setCartCount(count => count + 1)}>
Add Product
</button>
</div>
);
}
export default Cart;
When the user clicks the button, React updates the state and displays the new cart count. React decides which DOM changes are needed.
13. Frequently Asked Interview Questions
Q1. What is the Real DOM?
The Real DOM is the browser-maintained tree representation of an HTML document. JavaScript can access and modify its nodes, text, attributes, and styles.
Q2. What is the Virtual DOM?
The Virtual DOM is an in-memory representation of the UI that React uses to calculate the changes required to update the browser DOM.
Q3. What is the main difference between the Real DOM and Virtual DOM?
The Real DOM is the actual browser document structure. The Virtual DOM is a representation React uses to determine the required updates to that structure.
Q4. Why does React use a Virtual DOM approach?
It allows developers to describe the desired UI declaratively and lets React calculate and apply the required DOM changes, instead of requiring developers to manually update each element.
Q5. What is reconciliation?
Reconciliation is the process React uses to compare rendered UI results and determine what changes are needed.
Q6. Does React always update the entire DOM?
No. React generally commits only the necessary DOM changes. If the rendered result has not changed, it may not update the DOM.
Q7. Is the Virtual DOM always faster?
No. It can help reduce unnecessary DOM operations, but rendering and reconciliation have their own costs. Performance depends on the application and how it is implemented.
Q8. What is the difference between Virtual DOM and Shadow DOM?
The Virtual DOM is a UI representation used by React. The Shadow DOM is a browser feature that encapsulates a DOM subtree and its styles.
Q9. Can we access the Real DOM in React?
Yes. Developers can use refs, such as useRef(), when they need to focus, measure, or interact with a DOM node.
Q10. What triggers a React re-render?
A component can re-render when its state changes, when its parent renders and it is rendered again, or when relevant context changes. A re-render does not necessarily mean a DOM mutation will occur.
14. Quick Revision Notes
- DOM: Document Object Model.
- Real DOM: The actual document structure managed by the browser.
- Virtual DOM: An in-memory UI representation used by React.
- JSX: A syntax used to describe UI in React.
- Re-render: React calculates the component's UI output again.
- Reconciliation: React determines the differences between rendered UI results.
- Commit: React applies the necessary changes to the browser DOM.
- useState: A Hook used to store component state.
- useRef: A Hook often used to reference DOM nodes or store values that do not trigger a render.
- Key takeaway: React manages DOM updates based on the UI described by your components.
15. Practice Tasks
- Create an HTML page and use JavaScript to change a heading when a button is clicked.
- Create a React component that changes heading text using
useState().
- Build a counter with Increase and Decrease buttons.
- Create a shopping cart counter that increases when a product is added.
- Use
useRef() to focus an input field when a button is clicked.
- Use your browser's developer tools to inspect the Real DOM before and after an update.
16. Conclusion
The Real DOM is the actual document structure maintained by the browser, while the Virtual DOM is an in-memory UI representation used by React. React renders components, compares the resulting UI with the previous result, and commits the necessary changes to the Real DOM.
For React development, the recommended approach is to manage ordinary UI changes through state, props, and components. Use direct DOM access only when needed for tasks such as focusing inputs, measuring elements, or integrating browser APIs.
Learn React JS with JustAcademy
Explore the JustAcademy React JS Training Course to learn React concepts and build modern web applications.
Interested in a demo? Register for the React JS Course Demo.
Official Reference